package com.daiyang.campus_lucky_draw.contreller;

import com.daiyang.campus_lucky_draw.common.error.ControllerErrorCodeConstants;
import com.daiyang.campus_lucky_draw.common.exception.ControllerException;
import com.daiyang.campus_lucky_draw.common.result.CommonReslut;
import com.daiyang.campus_lucky_draw.common.utils.JacksonUtil;
import com.daiyang.campus_lucky_draw.contreller.param.CreateActivityParam;
import com.daiyang.campus_lucky_draw.contreller.param.PageListParam;
import com.daiyang.campus_lucky_draw.contreller.result.CreateActivityResult;
import com.daiyang.campus_lucky_draw.contreller.result.FindActivityDetailResult;
import com.daiyang.campus_lucky_draw.contreller.result.FindActivityListResult;
import com.daiyang.campus_lucky_draw.service.ActivityService;
import com.daiyang.campus_lucky_draw.service.dto.ActivityDTO;
import com.daiyang.campus_lucky_draw.service.dto.ActivityDetailDTO;
import com.daiyang.campus_lucky_draw.service.dto.CreateActivityDTO;
import com.daiyang.campus_lucky_draw.service.dto.PageListDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ActivityController {
    private static final Logger logger =
            LoggerFactory.getLogger(ActivityController.class);
    @Autowired
    private ActivityService activityService;
    /**
     * 创建活动
     *
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonReslut<CreateActivityResult> createActivity(
            @Validated @RequestBody CreateActivityParam param) {
        logger.info("createActivity CreateActivityParam: " +
                JacksonUtil.writeValueAsString(param));
        CreateActivityDTO createActivityDTO =
                activityService.createActivity(param);
        return
                CommonReslut.success(convertToCreateActivityResult(createActivityDTO));
    }
    private CreateActivityResult
    convertToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if(null == createActivityDTO) {
            throw new
                    ControllerException(ControllerErrorCodeConstants.ACTIVITY_CREATE_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(createActivityDTO.getActivityId());
        return result;
    }
    //查询活动列
    @RequestMapping("/activity/find-list")
    public CommonReslut<FindActivityListResult> findActivityList(PageListParam
                                                                         param) {
        logger.info("findActivityList FindActivityListParam: " +
                JacksonUtil.writeValueAsString(param));
        PageListDTO<ActivityDTO> findActivityListDTO =
                activityService.findActivityList(param);
        return
                CommonReslut.success(convertToFindActivityListResult(findActivityListDTO));
    }

    /**
     * 查询活动详细信息：奖品列表，⼈员列表
     *
     * @param activityId
     * @return
     * */
    @RequestMapping("/activity-detail/find")
    public CommonReslut<FindActivityDetailResult> findActivityDetail(Long activityId) {
        logger.info("getActivity activityId: " + activityId);
        ActivityDetailDTO activityDetailDTO =
                activityService.getActivityDetail(activityId);
        return
                CommonReslut.success(convertToGetActivityResult(activityDetailDTO));
    }

    private FindActivityDetailResult convertToGetActivityResult(ActivityDetailDTO activityDetailDTO) {
        logger.info("convertToGetActivityResult activityDetailDTO: {}", JacksonUtil.writeValueAsString(activityDetailDTO));
        if(null==activityDetailDTO){
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }
        FindActivityDetailResult result = new FindActivityDetailResult();
        result.setActivityId(activityDetailDTO.getActivityId());
        result.setActivityName(activityDetailDTO.getActivityName());
        result.setDescription(activityDetailDTO.getDesc());
        result.setValid(activityDetailDTO.valid());
        // 抽奖顺序：一等奖、二等奖、三等奖
        result.setPrizes(activityDetailDTO.getPrizeDTOList().stream()
                //排序
                .sorted(Comparator.comparingInt(prizeDTO->prizeDTO.getTiers().getCode()))
                .map(prizeDTO -> {
                    FindActivityDetailResult.Prize prize = new FindActivityDetailResult.Prize();
                    prize.setPrizeId(prizeDTO.getPrizeId());
                    prize.setName(prizeDTO.getName());
                    prize.setDescription(prizeDTO.getDescription());
                    prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                    prize.setImageUrl(prizeDTO.getImageUrl());
                    prize.setValid(prizeDTO.valid());
                    prize.setPrice(prizeDTO.getPrice());
                    return prize;
                }).collect(Collectors.toList())
        );

        // 人员信息
        result.setUsers(activityDetailDTO.getUserDTOList().stream()
                .map(UserDTO -> {
                    FindActivityDetailResult.User user = new FindActivityDetailResult.User();
                    user.setUserId(UserDTO.getUserId());
                    user.setUserName(UserDTO.getUserName());
                    user.setValid(UserDTO.valid());
                    return user;
                }).collect(Collectors.toList())
        );
        return result;

    }

    private FindActivityListResult
    convertToFindActivityListResult(PageListDTO<ActivityDTO> findActivityListDTO) {
        if (null == findActivityListDTO) {
            throw new
                    ControllerException(ControllerErrorCodeConstants.ACTIVITIES_FIND_ERROR);
        }
        FindActivityListResult result = new FindActivityListResult();
        result.setTotal(findActivityListDTO.getTotal());
        result.setRecords(findActivityListDTO.getRecords()
                .stream()
                .map(dto -> {
                    FindActivityListResult.ActivityInfo activityInfo = new
                            FindActivityListResult.ActivityInfo();
                    activityInfo.setActivityId(dto.getActivityId());
                    activityInfo.setActivityName(dto.getActivityName());
                    activityInfo.setDescription(dto.getDescription());
                    activityInfo.setValid(dto.valid());
                    return activityInfo;
                }).collect(Collectors.toList()));
        return result;
    }
}